﻿using BCCommon;
using BCCommon.Enums;
using BCDto.TMS.Driver;
using BCDto.Website.User;
using BCService.TMS.Driver;
using BCService.Website.User;
using BCTMSRESTful.Configs;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;

namespace BCTMSRESTful.Controllers.DriverApp
{
    [RequireAuthorize(RoleType.Driver)]
    public class DriverAppBaseController : BCTMSRESTfulAPIController
    {
        private IRedisService redisService;
        private IDriverService driverService;
        private IUserService userService;
        public UserDto UserInfo { get; private set; }
        public DriverDto Driver { get; private set; }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            HttpContext httpContext = context.HttpContext;

            if (httpContext.User.Identity.IsAuthenticated && httpContext.User.Identity.Name.StartsWith("Driver:"))
            {
                long userId;
                if (long.TryParse(httpContext.User.Identity.Name.Substring(7), out userId))
                {
                    #region 初始化服务

                    driverService = httpContext.RequestServices.GetService<IDriverService>();
                    redisService = httpContext.RequestServices.GetService<IRedisService>();
                    userService = httpContext.RequestServices.GetService(typeof(IUserService)) as IUserService;                    

                    #endregion
                    this.UserInfo = userService.GetUserByUserId(userId);
                    this.Driver = driverService.GetDriverByUserId(userId);
                }
                if (this.Driver == null)
                {
                    context.Result = this.Forbid();
                }
            }
            base.OnActionExecuting(context);
        }
    }
}
